package com.tg.app.push;

import static com.tg.appcommon.android.TGApplicationBase.getApplicationContext;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.EventConstants;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.R;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.base.WebBaseActivity;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.activity.device.NoDeviceActivity;
import com.tg.app.util.LogUtils;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.business.IMessageModule;
import com.tg.appcommon.helper.LogoutDialogHelper;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.data.http.entity.PushEventBean;
import com.tg.message.msg.MessageDataHolder;
import com.tg.message.msg.MessagePlayActivity;
import com.tg.push.PushManager;
import com.tg.push.TGCorePushReceiver;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

public class TangeMessageReceiver extends TGCorePushReceiver {

    public static final String TAG = "TangeMessageReceiver";

    @Override
    public void onNotificationMessageOpened(Context context, String title, String summary, String extraMap) {

        TGLog.i(TAG, "[onNotificationMessageOpened] title = " + title);
        TGLog.i(TAG, "[onNotificationMessageOpened] summary = " + summary);
        TGLog.i(TAG, "[onNotificationMessageOpened] extraMap = " + extraMap);

        PushEventBean eventBean = null;

        try {
            eventBean = JSONObject.parseObject(extraMap, PushEventBean.class);
        } catch (Throwable ex) {
            TGLog.i(TAG, "[onNotificationMessageOpened] error while parse json = " + ex);
        }

        if (eventBean == null){
            return;
        }

        DeviceItem item = new DeviceItem();
        item.uuid = eventBean.uuid;
        item.id = eventBean.device_id;
        item.image_path = eventBean.image_path;

        openNotificationActivity(context,eventBean,item, extraMap);
    }

    /**
     * 负责消息分发，可能是通知栏点击、也可能是长连接推送，也可能是FCM透传（应用在前台）
     *
     * @param context
     * @param eventBean
     * @param item
     */
    public static void openNotificationActivity(Context context, PushEventBean eventBean, DeviceItem item) {
        openNotificationActivity(context, eventBean, item, false, null);
    }

    public static void openNotificationActivity(Context context, PushEventBean eventBean, DeviceItem item, String extraMap) {
        openNotificationActivity(context, eventBean, item, false, extraMap);
    }

    public static void openNotificationActivity(Context context, PushEventBean eventBean, DeviceItem item, boolean callFromDeviceListPage, String extraMap) {
        TGLog.i(TAG, "openNotificationActivity: callFromDeviceListPage = " + callFromDeviceListPage);
        TGLog.i(TAG, "openNotificationActivity: eventBean = " + JSON.toJSONString(eventBean));

        if (eventBean == null) return;

        if (eventBean.user_id > 0 && eventBean.user_id != PreferenceUtil.getInt(context, CommonConstants.PRE_USER_ID) || eventBean.alert_type == PushConstants.TYPE_SECURITY) {
            TGLog.i(TAG, "openNotificationActivity: not same user");
            return;
        }

        TGLog.i(TAG, "eventBean.tag = " + eventBean.tag);



        TGLog.i(TAG, "openNotificationActivity: go to normal message page.");
        if (StringUtils.equalsIgnoreCase(eventBean.tag, EventConstants.NEW_SHARE_APPID)){
            LogUtils.onEventClickByName("device_list", "card_share");
            Intent intent = new Intent();
            DeviceSettingsInfo info = new DeviceSettingsInfo();
            long deviceId = item != null ? item.id : 0;
            if (deviceId == 0){
                deviceId = eventBean.device_id;
            }
            info.deviceID = deviceId;
            info.uuid = item != null ? item.uuid : "";
            intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
            intent.putExtra(WebBaseActivity.KEY_WEBURL, eventBean.url);
            intent.putExtra(WebBaseActivity.KEY_WEBTITLE, "");
            intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
            intent.setClass(context, CloudServiceActivity.class);
            if (!(context instanceof Activity)){
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
            return;
        }
        openMessageActivity(context, eventBean, item);

    }

    public static void openMessageActivity(Context context, PushEventBean eventBean, DeviceItem item) {
        MessageDataBean.ItemsBean message = new MessageDataBean.ItemsBean();
        message.setStart_time(eventBean.start_time);
        message.setStart_ts(eventBean.start_ts);
        message.setTag(eventBean.tag);
        message.setUuid(eventBean.uuid);
        message.setMessage_type(eventBean.message_type);
        message.setIs_ai_tag(eventBean.is_ai_tag);
        message.setIs_pay(eventBean.is_pay);
        message.setRequestid(eventBean.requestid);
        message.setSimilarityDegree(eventBean.similarity_degree);
        if (StringUtils.isEmpty(eventBean.similarity_degree)){
            message.setSimilarityDegree(eventBean.subclass);
        }

        if (!TextUtils.equals(eventBean.message_type, EventConstants.NOTICE)) {
            message.setTag_msg(eventBean.tag_msg);
            message.setImage_path(eventBean.image_path);
            message.setIs_pay(eventBean.is_pay);
            message.setOssid(eventBean.ossid);
            message.setAddr(eventBean.addr);
            message.setPos(eventBean.pos);
        } else {
            message.setTag_msg(eventBean.tag_msg);
            message.setBtn_style(eventBean.btn_style);
            message.setBtn_name(eventBean.btn_name);
            message.setTag_name(eventBean.tag_name);
            message.setUrl(eventBean.url);
        }

        message.setTag_name(eventBean.tag_name);
        message.setTag_msg(eventBean.tag_msg);

        message.setDevice_id(String.valueOf(eventBean.device_id));
        message.setNickname(eventBean.nickname);
        message.setMessage(eventBean.message);

        if (TextUtils.equals(message.getTag(), "body")) {
            message.setIs_body(2);
        }
        long diff = 61;
        //guid存在，或开始时间大于1分钟
        Intent i = new Intent();
        i.putExtra(IMessageModule.EXT_EVENT_MESSAGE, message);
        i.putExtra(IMessageModule.EXT_DEVICE_DES, eventBean.des_key);
        i.putExtra(MessageDataHolder.EXT_PUSH_ORIGIN, MessageDataHolder.PUSH_ORIGIN_JPUSH);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        i.setClass(context, MessagePlayActivity.class);
        context.startActivity(i, ActivityOptions.makeCustomAnimation(context, R.anim.push_botton_in, R.anim.push_botton_out).toBundle());
    }


    private void getBitmapAsyncAndDoWork(Context context ,NotificationCompat.Builder builder ,String imageUrl) {
        final  int id = (int) (System.currentTimeMillis()/10000);
        Glide.with(getApplicationContext())
                .asBitmap()
                .load(imageUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                       if (resource!=null){
                           builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(resource));
                           builder.setLargeIcon(resource);
                           NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
                           notificationManager.notify(id, builder.build());
                       }
                    }

                    @Override
                    public void onLoadCleared(Drawable placeholder) {
                    }

                    @Override
                    public void onLoadFailed(Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher));
                        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
                        notificationManager.notify(id, builder.build());
                    }
                });
    }

    private void fcmNotification(Context context,String title ,String body,String extraMap){
        Intent intent = new Intent(context, DeviceListActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        HashMap<String,Object> objectHashMap = JSON.parseObject(extraMap,HashMap.class);
        try {
            Bundle bundle = mapToBundle(objectHashMap);
            intent.putExtras(bundle);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            String notificationId = "1";
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, notificationId)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.drawable.ic_tange_push_icon)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);
            getBitmapAsyncAndDoWork(context,builder,bundle.getString("image_path"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Bundle mapToBundle(Map<String, Object> data) throws Exception {
        Bundle bundle = new Bundle();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String)
                bundle.putString(entry.getKey(), (String) entry.getValue());
            else if (entry.getValue() instanceof Double) {
                bundle.putDouble(entry.getKey(), ((Double) entry.getValue()));
            } else if (entry.getValue() instanceof Integer) {
                bundle.putInt(entry.getKey(), (Integer) entry.getValue());
            } else if (entry.getValue() instanceof Float) {
                bundle.putFloat(entry.getKey(), ((Float) entry.getValue()));
            }
        }
        return bundle;
    }

    private static PushEventBean lastArrivedPush;

    @Override
    public void onNotificationMessageArrived(Context context, String title, String summary, String extraMap) {

        TGLog.i(TAG, "[onNotificationMessageArrived] title = " + title + ", summary = " + summary + ", extraMap = " + extraMap);

        PushEventBean itemsBean;

        try {
            itemsBean = JSONObject.parseObject(extraMap, PushEventBean.class);
        } catch (Throwable ex) {
            TGLog.i(TAG, "[onNotificationMessageArrived] error while parse : " + ex);
            return;
        }

        // 过滤重复消息（比如长连接和消息推送透传两个渠道同时来消息）
        if (lastArrivedPush != null && itemsBean != null) {
            if (lastArrivedPush.start_ts == itemsBean.start_ts && lastArrivedPush.device_id == itemsBean.device_id) {
                TGLog.i(TAG, "[onNotificationMessageArrived] ignore duplicated message.");
                return;
            }
        }



        TGLog.i(TAG, "[onNotificationMessageArrived] itemsBean = " + itemsBean);

        if (itemsBean != null) {
            lastArrivedPush = itemsBean;
            {
                TGLog.i(TAG, "[onNotificationMessageArrived] normal message");

                if (PushManager.isFcm()) {
                    fcmNotification(context, title, summary, extraMap);
                }

                if (itemsBean.alert_type == PushConstants.TYPE_SHARE || itemsBean.alert_type == PushConstants.TYPE_UNSHARE) {
                    Intent intent = new Intent();
                    intent.setAction(NoDeviceActivity.ACTION_DEVICE_SHARE);
                    context.sendBroadcast(intent);
                    return;
                }

                if (itemsBean.alert_type == 0) return;

                try {
                    org.json.JSONObject object = new org.json.JSONObject(extraMap);
                    switch (itemsBean.alert_type) {
                        case PushConstants.TYPE_SECURITY:
                            String timeStr = object.optString("time");
                            long pushTime = Long.valueOf(timeStr);
                            long lastLogin = PreferenceUtil.getLong(context, CommonConstants.PRE_USER_LOGIN_UPDATED_AT) / 1000;
                            if (pushTime < lastLogin) {
                                return;
                            }
                            PreferenceUtil.setInt(context, CommonConstants.PRE_USER_ID, 0);
                            Intent offlineIntent = new Intent();
                            offlineIntent.setAction(CommonConstants.ACTION_INTENT_USER_OFFLINE);
                            context.sendBroadcast(offlineIntent);
                            String time = DateUtil.getStrToTimeHm(timeStr);
                            LogoutDialogHelper.getInstance().showLogoutDialog(time);
                            break;
                        case PushConstants.TYPE_ONLINE:
                            Intent onlineIntent = new Intent();
                            onlineIntent.putExtra(SocketIoConstants.NOTIFY_KEY_DATA, JSON.toJSONString(extraMap));
                            onlineIntent.setAction(SocketIoConstants.NOTIFY_DEVICE_STATUS);
                            context.sendBroadcast(onlineIntent);
                            break;
                        default:
                            Intent intent = new Intent();
                            intent.setAction(DeviceListActivity.ACTION_UPDATE_LIST);
                            context.sendBroadcast(intent);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
